package com.example.shardingjdbc.quartz;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author :ludiguang
 * @Description:
 * @date :2023/5/5 9:10
 */
@Slf4j
@Configuration
@EnableScheduling
public class ShardingJDBCJob {
    @Resource
    private JdbcTemplate jdbcTemplate;

    // 定义表创建SQL语句，用当前日期动态生成表名
    private static final String CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS jy_{date} (\n" +
            "id bigint NOT NULL AUTO_INCREMENT COMMENT 'ID',\n" +
            "equip_ip varchar(20) DEFAULT NULL COMMENT '设备IP',\n" +
            "port_index varchar(10) DEFAULT NULL COMMENT '端口',\n" +
            "port_in_flow decimal(20) DEFAULT NULL COMMENT '端口入流量',\n" +
            "port_send_flow decimal(20) DEFAULT NULL COMMENT '端口出流量',\n" +
            "port_flow decimal(20) DEFAULT NULL COMMENT '端口额定流量',\n" +
            "create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n" +
            "PRIMARY KEY (id)\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='jy_{date}';";

    //每天晚上23点跑一次
    @Scheduled(cron = "0 0 23 * * ?", zone = "Asia/Shanghai")
    public void test() {
        try {
            // 获取当前日期加1天
            LocalDateTime currentDateTime = LocalDateTime.now().plusDays(1);
            // 格式化日期，生成表名
            String tableName = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            // 替换占位符为表名
            String createTableSql = CREATE_TABLE_SQL.replace("{date}", tableName);
            // 执行SQL语句，创建表
            jdbcTemplate.execute(createTableSql);
        } catch (Exception e) {
            log.error("执行定时任务出错：{}", e.getMessage());
        }
    }
}